package com.chixing.ih.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @author 刘岩
 * @version 1.0
 * @Desc Practice makes perfect
 * @date 2020/9/10 14:17
 */
public class GenerateOrderNoUtil {

    /**
     * 生成订单号
     * yyyyMMddHHmmss 6位随机  4位用户id
     *
     * @return
     */
    public static String getGenerateOrderNo(Long userId) {
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StringBuffer stringBuffer = new StringBuffer(userId.toString());
        //id长度大于4  取后四位
        if (stringBuffer.length() > 4) {
            stringBuffer = new StringBuffer(stringBuffer.substring(stringBuffer.length() - 4, stringBuffer.length()));
        }
        //长度小于4  补全4位
        while (stringBuffer.length() < 4) {
            stringBuffer.insert(0, "0");
        }
        return time + getNumber() + stringBuffer.toString();
    }

    public static int getNumber() {
        int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Random rand = new Random();
        for (int i = 10; i > 1; i--) {
            int index = rand.nextInt(i);
            int tmp = array[index];
            array[index] = array[i - 1];
            array[i - 1] = tmp;
        }
        int result = 0;
        for (int i = 0; i < 6; i++) {
            result = result * 10 + array[i];
        }
        if (String.valueOf(result).length() == 6) {
            return result;
        } else {
            return getNumber();
        }
    }
}
